package com.draw.cli.gui.panel.config;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.draw.cli.config.ConfigManager;

public class ProxyConfigPanel extends JPanel implements ActionListener {
	private static final long serialVersionUID = -7297893467776457728L;

	private JCheckBox enabled;
	private JTextField server;
	private JTextField port;

	public ProxyConfigPanel() {
		this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
		this.setBorder(BorderFactory.createTitledBorder("Proxy"));

		JPanel pan;
		
		pan = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pan.add(new JLabel("Activé :"));
		this.enabled = new JCheckBox();
		this.enabled.addActionListener(this);
		pan.add(this.enabled);
		this.add(pan);

		pan = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pan.add(new JLabel("Serveur :"));
		this.server = new JTextField(10);
		pan.add(this.server);
		this.add(pan);

		pan = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pan.add(new JLabel("Port :"));
		this.port = new JTextField(5);
		pan.add(this.port);
		this.add(pan);
		
		this.refresh();
	}
	
	public void refresh () {
		this.enabled.setSelected(ConfigManager.getInstance().isProxyEnabled());
		this.server.setEnabled(this.enabled.isSelected());
		this.port.setEnabled(this.enabled.isSelected());
		this.server.setText(ConfigManager.getInstance().getProxyServer());
		this.port.setText(ConfigManager.getInstance().getProxyPort()+"");
	}
	
	public void ok () {
		ConfigManager.getInstance().setProxyEnabled(this.enabled.isSelected());
		ConfigManager.getInstance().setProxyServer(this.server.getText());
		ConfigManager.getInstance().setProxyPort(Integer.parseInt(this.port.getText()));
		this.refresh();
	}
	
	public void cancel () {
		this.refresh();
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (this.enabled.equals(arg0.getSource())) {
			this.server.setEnabled(this.enabled.isSelected());
			this.port.setEnabled(this.enabled.isSelected());
		}
	}
}
